package com.example.demo.dto;

import java.util.concurrent.*;
import com.alibaba.ttl.threadpool.TtlExecutors;

/**
 * 线程池工具类
 *
 * @author zzb
 * @create 2017/12/22 12:02
 **/
public class ThreadPoolUtil {


    public static ThreadPoolExecutor threadPool = null;
    /**
     * 线上并行请求用这个
     */
    private static final ExecutorService parallelRequestExecutor;

    static {
        int nCpu = Runtime.getRuntime().availableProcessors();
        int corePoolSize = (2 * nCpu) + 1;
        threadPool = new ThreadPoolExecutor(corePoolSize, corePoolSize, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

        parallelRequestExecutor = TtlExecutors.getTtlExecutorService(new ThreadPoolExecutor(
                new Float(nCpu / 0.1).intValue(),
                new Float(nCpu / 0.1).intValue(),
                0,
                TimeUnit.SECONDS,
                new SynchronousQueue<>(),
                new CommonThreadFactory("ParallelRequest"),
                new ThreadPoolExecutor.CallerRunsPolicy()));
    }

    public static ExecutorService getParallelThreadPool() {
        return parallelRequestExecutor;
    }

}
